<template>
  <div>
    <el-page-header @back="goBack" content="商品详情"></el-page-header>

    <el-skeleton v-if="loading" style="padding: 20px;">
      <template #template>
        <div style="height: 380px; border-radius: 8px;"></div>
        <div style="margin-top: 20px; height: 300px;"></div>
      </template>
    </el-skeleton>

    <div v-else class="banner_movie">
      <img :src="movie.img?.trim()" class="movie-poster" :alt="`商品${movie.gid}-${movie.gname}`">
      <div class="movie-info">
        <h1>{{ movie.gname }}</h1>
        <p>类型：{{ movie.type }}</p>
        <p>价格：<span class="price">{{ movie.price }}元</span></p>
        <p>时长：{{ movie.duration }}</p>
        <p>作者：{{ movie.author }}</p>
        <el-tag type="warning" size="large">积分要求：{{ movie.scorerequired }}</el-tag>

        <el-button :icon="isCollect ? StarFilled : Star" @click="changeCollect" class="collectBtn"
          :type="isCollect ? 'danger' : 'info'" disabled>
          {{ count }}
        </el-button>

        <div class="cart-controls">
          <el-input-number v-model="num" :min="1" :max="10" controls-position="right" />
          <el-button type="primary" @click="addShopCart" class="add-cart-btn">
            加入购物车
          </el-button>
        </div>
      </div>
    </div>

    <el-tabs v-model="activeName" class="detail-tabs">
      <el-tab-pane label="介绍" name="first">{{ movie.describe1 }}</el-tab-pane>
      <el-tab-pane label="评论" name="second">
        <div class="empty-comment">暂无评论</div>
      </el-tab-pane>
      <el-tab-pane label="演职员" name="third">
        <p>作者：{{ movie.author || '暂无信息' }}</p>
      </el-tab-pane>
      <el-tab-pane label="图集" name="fourth">
        <div v-if="movie.img" class="movie-image-gallery">
          <img :src="movie.img?.trim()" :alt="`商品${movie.gid}-${movie.gname}`" class="gallery-image">
        </div>
        <div v-else>暂无图片</div>
      </el-tab-pane>
    </el-tabs>
  </div>
</template>

<script setup>
import { ref, onMounted } from 'vue'
import { useRouter, useRoute } from 'vue-router'
import { Star, StarFilled } from '@element-plus/icons-vue'
import { ElMessage } from 'element-plus'
import request from '@/utils/request'

const num = ref(1)
const count = ref(0)
const isCollect = ref(false)
const movie = ref({})
const activeName = ref('first')
const route = useRoute()
const router = useRouter()
const loading = ref(true)


onMounted(() => {
  console.log("获取路由携带参数：", route.query.gid);
  if (route.query.gid) {
    getMovieById()
  } else {
    ElMessage.error("未找到商品gid")
    router.go(-1)
  }
})

const getMovieById = async () => {
  try {
    loading.value = true
    console.log("调用方法getMovieById，gid：", route.query.gid);
    const goodsData = await request.get(`/goods/getMovieById/${route.query.gid}`)

    console.log("接口返回的商品原始数据：", goodsData);

    if (goodsData && goodsData.gid) {
      movie.value = goodsData
      console.log("成功获取商品数据：", movie.value);
    } else {
      ElMessage.error("获取的商品数据无效")
      console.error("商品数据无效：", goodsData);
    }
  } catch (error) {
    console.error("获取商品数据时发生错误：", error)
    ElMessage.error("网络错误，无法获取商品信息")
  } finally {
    loading.value = false
  }
}

const getCollect = async () => {

    const data = await request.get("/collect/getCollect", {
        params: {
            gid: route.query.gid,
            uid: sessionStorage.getItem("uid")
        }
    })
    console.log("收藏数量：", data);
    isCollect.value = !!data//将任何非空值转换为 true

}

// 收藏or取消收藏
const changeCollect = async () => {
    // 检查用户是否登录
    const token = localStorage.getItem("token")
    if (!token) {
        ElMessage.warning("请先登录")
        // 跳转到登录页面
        router.push("/login")
        return
    }
    isCollect.value = !isCollect.value
    const gid = route.query.gid
    console.log(gid);

    // 发起请求，携带json参数，后端接收消息体对象
    const data = await request.post("/collect/changeCollect", {
        mid: route.query.gid,
        uid: localStorage.getItem("uid")
    })
    console.log("收藏状态：", data);

    if (data === 1) {
        ElMessage.success("收藏成功")
    } else {
        ElMessage.info("取消成功")
    }
    await countCollect()

}
// 显示收藏数
const countCollect = async () => {
    try {
        const data = await request.get("/collect/countCollect", {
            params: { gid: route.query.gid }
        })
        count.value = data
        console.log("收藏数量：", data);

    } catch (error) {
        console.error('获取收藏数量失败', error)
    }
}

// 加入购物车
const addShopCart = async () => {
    // 检查用户是否登录
    const token = localStorage.getItem("token")
    if (!token) {
        ElMessage.warning("请先登录")
        // 跳转到登录页面
        router.push("/login")
    }
    // 以下修改自己的添加购物车逻辑
    // const data = await request.post("/shopCart/addShopCart", {
    //     mid: route.query.id,
    //     uid: localStorage.getItem("uid"),
    //     num: num.value
    // })
    // if (data) {
    //     ElMessage.success("加入成功")
    // } else {
    //     ElMessage.error("加入失败")
    // }
  
}

const goBack = () => {
  router.go(-1)
}
</script>

<style scoped>
.banner_movie {
  display: flex;
  align-items: center;
  margin: 20px auto;
  width: 80%;
  background-color: #f8f9fa;
  padding: 30px;
  border-radius: 12px;
  box-shadow: 0 4px 16px rgba(0, 0, 0, 0.1);
}

.movie-poster {
  width: 280px;
  height: auto;
  border-radius: 8px;
  object-fit: cover;
  margin-right: 40px;
  box-shadow: 0 4px 8px rgba(0, 0, 0, 0.1);
}

.movie-info {
  flex: 1;
  color: #333;
}

.movie-info h1 {
  font-size: 32px;
  color: #333;
  margin-bottom: 20px;
  font-weight: 600;
}

.movie-info p {
  margin: 10px 0;
  font-size: 16px;
  line-height: 1.6;
}

.price {
  color: #e63946;
  font-weight: bold;
  font-size: 20px;
}

.cart-controls {
  display: flex;
  align-items: center;
  gap: 20px;
  margin-top: 30px;
}

.add-cart-btn {
  height: 40px;
  padding: 0 24px;
  font-size: 16px;
}

.collectBtn {
  background-color: transparent;
  border: none;
  color: #6c757d;
  padding: 8px 15px;
  font-size: 1.1em;
  margin-top: 15px;
  transition: all 0.3s;
}

.collectBtn:hover {
  transform: scale(1.05);
  color: #e63946;
}

.detail-tabs {
  width: 80%;
  margin: 30px auto;
  background: white;
  padding: 20px;
  border-radius: 8px;
  box-shadow: 0 2px 12px rgba(0, 0, 0, 0.1);
}

.empty-comment {
  text-align: center;
  padding: 50px;
  color: #999;
}

.movie-image-gallery {
  padding: 20px;
  text-align: center;
}

.gallery-image {
  max-width: 100%;
  border-radius: 8px;
  box-shadow: 0 2px 10px rgba(0, 0, 0, 0.1);
}
</style>